package cn.fws.meap.community.web;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.fws.framework.utils.UUIDUtils;
import cn.fws.meap.community.vo.Details;
import cn.fws.meap.community.vo.ProblemListVo;
import cn.fws.meap.system.constants.WeChat;
import cn.fws.meap.user.entity.AccountRecord;
import cn.fws.meap.user.enums.AccountRecordTypeEnums;
import cn.fws.meap.user.enums.ConsumptionEnums;
import cn.fws.meap.user.service.IAccountRecordService;
import cn.fws.meap.utils.MD5Until;
import cn.fws.meap.utils.WeChatPayUtils;
import cn.fws.meap.utils.WechatUtils;
import cn.fws.meap.utils.logBug.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import cn.fws.meap.community.entity.Problem;
import cn.fws.meap.community.service.IProblemService;
import cn.fws.framework.utils.StringUtils;
import cn.fws.framework.web.contoller.BaseController;
import cn.fws.framework.web.page.PagingResult;
import cn.fws.framework.web.contoller.JsonResponse;

import static cn.fws.meap.utils.HttpUtil.formatUrlMap;

/**
 * 问题 信息操作处理
 *
 * @author chenkh
 * @date 2019-03-07
 */
@RestController
@RequestMapping("/meap/problem")
@Api(tags = "问题 信息操作处理")
public class ProblemController extends BaseController {

    @Autowired
    private IProblemService problemService;

    @Autowired
    private IAccountRecordService accountRecordService;

    private boolean addAccountStatus;

    @Value("${serverIP}")
    private String notify_url;//回调ip
    /**
     * 查询问题列表
     */
    //@RequiresPermissions("meap:problem:list")
    @ApiOperation(value = "查询问题列表")
    @PostMapping("/list")               //1 热门问答 2最新问答
    public PagingResult<ProblemListVo> list(String hotProblem) {
        startPage();
        List<ProblemListVo> list = problemService.selectList(hotProblem);
        return getPagingResult(list);
    }
    
    /**
     * 查询问题详情
     */
    //@RequiresPermissions("meap:problem:list")
    @ApiOperation(value = "查询问题详情")
    @PostMapping("/getProblemMsg")
    public ProblemListVo getProblemMsg(String id,String openId) {
        ProblemListVo problemListVo = problemService.selectProblemById(id,openId);
        return problemListVo;
    }

    /**
     * 查询问题列表
     */
    //@RequiresPermissions("meap:problem:list")
    @ApiOperation(value = "查询最新的三条问题列表")
    @PostMapping("/listNew")
    public List<Details<Problem>> selectListNew() {

        List<Details<Problem>> list = problemService.selectListNew();
        return list;
    }


    /**
     * 新增保存问题
     */
    //@RequiresPermissions("meap:problem:add")
    @SysLog
    @ApiOperation(value = "新增保存问题")
    @ApiImplicitParam(name = "problem", value = "新增保存问题", dataType = "Problem")
    @PostMapping("/add")
    public JsonResponse addSave(Problem problem,String order) {
        String problemId ="";
        try{
            System.out.println("添加问题时得到的订单号"+order);


        if (StringUtils.isEmpty(problem.getProblemTitle())) {
            return toAjax(0,"404", "标题不能为空");
        }else if (StringUtils.isEmpty(problem.getProblemMsg())) {
            return toAjax(0,"404", "标题不能为空");
        }else if(problem.getProblemTitle().length()>100){
            return toAjax(0,"404", "标题字数不能超过100");
        }
        //没有赏金 new bigdemica(a).compareTo(new bigdemical(b)) >= 0  bigdemical.compareTo(bigdemical2)
        BigDecimal aa=BigDecimal.valueOf(0);//数字类型比较大小
        if(problem.getProblemProfit().compareTo(aa)==0){
            System.out.println("没有赏金，不添加账户消费记录");
        }else {

            addAccountStatus=true;
            //添加账户消费记录
            AccountRecord accountRecord = new AccountRecord();
            accountRecord.setOrder(order);
            accountRecord.setType(AccountRecordTypeEnums.PROBLEM_CONSUMPTION.getCode());
            accountRecord.setOpenid(problem.getOpenid());
            System.out.println(problem.getOpenid());
            accountRecord.setConsumption(ConsumptionEnums.EXPENDITURE.getCode());
            accountRecord.setAmount(problem.getProblemProfit());
            accountRecordService.insert(accountRecord,addAccountStatus);
        }
            problemId = problemService.insert(problem);


        }catch (Exception e) {
            //如果添加問題失敗了，手動回滾事物
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            Map paraMap = new HashMap();
            //设置请求参数(小程序ID)
            paraMap.put("appid", WeChat.APPID);
            //设置请求参数(商户号)
            paraMap.put("mch_id", WeChat.MCH_ID);
            //设置请求参数(随机字符串)
            paraMap.put("nonce_str", UUIDUtils.getUUID());
            //设置请求参数(商户订单号)
            paraMap.put("out_trade_no", order);
            //设置请求参数(商户退款单号)
            paraMap.put("out_refund_no", UUIDUtils.getUUID()+UUIDUtils.getUUID());
            //设置请求参数(订单金额)
            paraMap.put("total_fee", problem.getProblemProfit());
            //设置请求参数(退款金额)
            paraMap.put("refund_fee", problem.getProblemProfit());
            //TODO (这个回调地址 没有具体进行测试 需要写好逻辑 打版在测试)设置请求参数(通知地址)
            paraMap.put("notify_url", "http://"+notify_url+":6001/fws-meap-service/meap/pay/notifyWeiXinPay");
            //加上+key，并转换成大写
            String stringA = formatUrlMap(paraMap, false, false);
            String sign = MD5Until.md5Encrypt32Upper(stringA + "&key="+WeChat.PaySignKey).toUpperCase();
            problem.getProblemProfit();
            //調用微信的退錢接口
            String refund = WeChatPayUtils.refund(WeChat.APPID, WeChat.MCH_ID, sign, problem.getProblemProfit().intValue(), problem.getProblemProfit().intValue(), order);

            String result = WechatUtils.httpRequest(WeChat.REFUND_URL,"POST",refund);

            e.printStackTrace();

        }
        return JsonResponse.success("操作成功",problemId);
    }

    /**
     * 修改保存问题
     */
    //@RequiresPermissions("meap:problem:edit")
    @ApiOperation(value = "修改保存问题")
    @ApiImplicitParam(name = "problem", value = "修改保存问题", dataType = "Problem")
    @PutMapping("/edit")
    public JsonResponse editSave(Problem problem) {
        if (problem.getProblemTitle() == null || "".equals(problem.getProblemTitle())) {
            return toAjax(0, "404", "标题不能为空");
        }
        //在文章保存之前首先将文章内的资源保存
        if ((problem.getProblemMsg() != null && !"".equals(problem.getProblemMsg()))) {
            return toAjax(problemService.update(problem));
        }
        return toAjax(0, "404", "内容不能为空");
    }

    /**
     * 删除问题
     */
    //@RequiresPermissions("meap:problem:remove")
    @ApiOperation(value = "删除问题")
    @ApiImplicitParam(name = "ids", value = "根据id删除问题", dataType = "String")
    @DeleteMapping("/remove")
    public JsonResponse remove(@RequestBody String ids) {
        return toAjax(problemService.deleteByIds(ids));
    }

}
